package com.itheima.AOP;

import com.itheima.mapper.EmpLoginLogMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.LoginInfo;
import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class LoginAspectLog {
    @Autowired
    EmpLoginLogMapper empLoginLogMapper;
    //拦截LoginController.login方法 获取员工所有参数 并记录日志
    @Around("execution(* com.itheima.controller.LoginController.login(..))")
    public Object loginLog(ProceedingJoinPoint pjp) throws Throwable {
        //获取方法参数
        Object arg = pjp.getArgs()[0];
        Emp emp = (Emp) arg;
        //1.获取用户名
        String username = emp.getUsername();

        //2.获取密码
        String password = emp.getPassword();

        //3.获取员工登录时间
        LocalDateTime loginTime = LocalDateTime.now();

        //4.判断登陆是否成功
        Long start = System.currentTimeMillis();
        Result login = (Result) pjp.proceed();
        Long end = System.currentTimeMillis();
        Short isSuccess ;
        String jwt = null;
        if (login.getCode()== 1){
            isSuccess = 1;
            //5.获取jwt
            LoginInfo loginInfo = (LoginInfo) login.getData();
            jwt = loginInfo.getToken();
        }else {
            isSuccess = 0;
            jwt = null;
        }



        //6.获取耗时
        Long costTime = end - start;
        EmpLoginLog empLoginLog = new EmpLoginLog();
        empLoginLog.setUsername(username.toString());
        empLoginLog.setPassword(password.toString());
        empLoginLog.setLoginTime(loginTime);
        empLoginLog.setIsSuccess(isSuccess);
        empLoginLog.setJwt(jwt);
        empLoginLog.setCostTime(costTime);
        log.info("记录日志：" + empLoginLog.toString());
        //将日志记录到数据库
        empLoginLogMapper.insert(empLoginLog);
        return login;

    }
}
